﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Serialization;

namespace SendSMS
{
    class Program
    {
        static void Main(string[] args)
        {

            //            using (MemoryStream memStream = new MemoryStream(100))
            //            {
            //                XmlSerializer xs = new XmlSerializer(typeof(SMSResult));
            //                byte[] firstString = Encoding.UTF8.GetBytes(
            //                       @"<SystemMsg>
            //	                          <code>0</code>
            //	                          <msg>发送失败，失败原因：</msg> 
            //                         </SystemMsg>"
            //                );
            //                memStream.Write(firstString, 0, firstString.Length);
            //                memStream.Position = 0;
            //                var result = (SMSResult)xs.Deserialize(memStream);
            //                Console.ReadLine();
            //            }



            //string url = "http://10.188.15.66:88/smsd-ws/ws/rs/sms/send";
            //string smsNum = "13489195192";
            //string smsConent = "福州市局测试短信,收到用QQ转发给我吧！[阿旺]";

            string url = args[0];
            string smsNum = args[1];
            if (!IsMobilePhone(smsNum)) return;
            string smsConent = args[2];
            string[] sArray = null;
            string itemCode = null;
            if (!string.IsNullOrEmpty(args[3]))
            {
                sArray = Regex.Split(args[3], "|", RegexOptions.IgnoreCase);

                itemCode = "<orgCode>" + sArray[0] + "</orgCode>" +
                           "<businessCode>" + sArray[1] + "</businessCode>" +
                           "<deptCode>" + sArray[2] + "</deptCode>" +
                           "<personCode>" + sArray[3] + "</personCode>";
            }
            else
            {
                itemCode = "<orgCode>13500600</orgCode>" +
                           "<businessCode>7001</businessCode>" +
                           "<deptCode>135006001100</deptCode>" +
                           "<personCode>16001682</personCode>";
            }

            //SysLog.WriteSysLog("Url:[" + url + "], smsNum:[" + smsNum + "], Text:" + smsConent);

            SMSResult result = null;

            string smsPostData = "<SmsInfo>" + itemCode +
                "<receInfo>" + smsConent + "</receInfo>" +
                "<receTime>" + DateTime.Now.AddMilliseconds(5).ToString("yyyy/MM/dd HH:mm:ss") + "</receTime>" +
                "<sendFlag>0</sendFlag>" +
                "<sendTime>" + DateTime.Now.AddMilliseconds(10).ToString("yyyy/MM/dd HH:mm:ss") + "</sendTime>" +
                "<phoneDetail>" +
                    "<phoneNum>" + smsNum + "</phoneNum>" +
                    "<userType>0</userType>" +
                    "<userCode>123</userCode>" +
                    "<userName>ITIL</userName>" +
                "</phoneDetail>" +
                "</SmsInfo>";

            var wr = WebRequest.Create(url) as HttpWebRequest;
            wr.Timeout = 360000;
            wr.ReadWriteTimeout = 360000;
            wr.AllowAutoRedirect = false;
            wr.Method = "POST";
            wr.Proxy = null;

            wr.ContentType = "application/xml";

            byte[] byteArray = Encoding.UTF8.GetBytes(smsPostData);
            // Set the content length of the string being posted.
            wr.ContentLength = byteArray.Length;

            var postStream = wr.GetRequestStream();

            // Write to the request stream.
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // get response
            HttpWebResponse ws;

            try
            {
                ws = wr.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                SysLog.WriteSysLog("Error:" + e.ToString());
                ws = e.Response as HttpWebResponse;
            }

            HttpStatusCode code;
            if (ws == null)
            {
                code = HttpStatusCode.InternalServerError;
                SysLog.WriteSysLog("Error：" + code);
            }
            else
            {
                code = ws.StatusCode;
                if (code == HttpStatusCode.OK)
                {
                    var responseStream = ws.GetResponseStream();
                    XmlSerializer xs = new XmlSerializer(typeof(SMSResult));
                    result = (SMSResult)xs.Deserialize(responseStream);
                    responseStream.Close();
                }
                else 
                {
                    SysLog.WriteSysLog("Error：" + code);
                }
            }
            ws.Close();

            if (result.Code == 1)
            {
                SysLog.WriteSysLog(result.Message);
                //Console.WriteLine(result.Message);
            }
        }

        public static bool IsMobilePhone(string input)
        {
            Regex regex = new Regex("^1\\d{10}$");
            return regex.IsMatch(input);
        }

        private static string GetResponseBody(HttpWebResponse response)
        {
            //Encoding encoding;
            //try
            //{
            //    encoding = Encoding.GetEncoding(response.CharacterSet);
            //}
            //catch (ArgumentException)
            //{
            //    encoding = Encoding.Default;
            //}

            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[4096];

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to text
                    tempString = Encoding.UTF8.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            return sb.ToString();
        }

    }
}
